package cancel.nonpreemptive;

import annotation.GuardedBy;

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;

//应用，SocketUsingTask实现了“可取消接口”，
public abstract class SocketUsingTask<T> implements CancellableTask<T> {
    @GuardedBy("this")
    private Socket socket;
    protected synchronized void setSocket(Socket s) {
        socket = s;
    }
    //这里实现了非标准的取消，即关闭底层套接字。
    public synchronized void cancel() {
        try {
            if (socket != null)
                socket.close();
        } catch (IOException ignored) {
        }
    }
    //这里实现了返回自定义的FutureTask，并重写了其cancel方法，使其包含了非标准的取消，以及标准的取消。
    public RunnableFuture<T> newTask() {
        return new FutureTask<T>(this) {
            public boolean cancel(boolean mayInterruptIfRunning) {
                try {
                    SocketUsingTask.this.cancel();
                } finally {
                    return super.cancel(mayInterruptIfRunning);
                }
            }
        };
    }
}

